# 用户功能
import os

from db import read_data, save_data
from conf import USER_INFO_DIR, USER_PWD_DIR

login_user_dict = {
    'username': '',
    'role': ''
}


def get_username_pwd():
    role = 'user'
    for i in range(2):
        username = input("请输入用户名:>>>").strip()
        if not username.isidentifier():
            print("请不要输入非法字符！")
            continue
        password = input("请输入密码:>>>").strip()
        if len(password) > 10:
            print("密码不要超过10位！")
            continue
        break
    else:
        username, password = '', ''
    if username == 'lea4ning' and password == '147258':
        role = 'admin'
    return username, password, role


def creat_dict(**kwargs):
    user_dict = {}
    user_dict[kwargs.get('username')] = {**kwargs}
    return user_dict


def creat_path(tag, username):
    path = ''
    if tag == 'pwd':
        path = os.path.join(USER_PWD_DIR, f'{username}_pwd.json')
    elif tag == 'info':
        path = os.path.join(USER_INFO_DIR, f'{username}_info.json')
    return path


def creat_info():
    while True:
        age = ''
        hobby_list = []
        print("信息录入".center(30, '-'))
        print("中止输入请在输入性别后输入Q".center(30, '-'))
        male = input("请输入您的性别:>>>").strip()
        if male.upper() == 'Q':
            break
        if male not in ['male', 'female']:
            print("性别请输入[male / female] ！")
            continue
        age = input("请输入您的年龄:>>>").strip()
        if not age.isdigit() and int(age) >= 0:
            print("请输入正确的数字！")
            continue

        while True:
            hobby = input("请输入您的爱好(按Q退出):>>>").strip()
            if hobby in hobby_list:
                print(f"请不要重复输入爱好{hobby}！")
            if hobby.upper() == 'Q':
                break
            hobby_list.append(hobby)
        break
    return male, age, hobby_list


def register():
    username, password, role = get_username_pwd()
    # 如果为空，说明不符合格式，则登录失败
    if not username:
        return "注册失败！"
    if f"{username}_pwd.json" in os.listdir(USER_PWD_DIR):
        return f"该用户名{username}已被注册，请不要重复注册！"
    # 录入性别，年龄，爱好等信息
    male, age, hobby_list = creat_info()
    if age == '':
        return ''
    # 将信息保存到文件中
    info_dict = creat_dict(username=username, male=male, age=age, hobby=hobby_list)
    info_path = creat_path(tag='info', username=username)
    info_msg = save_data(info_dict, path=info_path)
    if info_msg:
        return info_msg
    # 将用户名密码保存到文件中
    user_dict = creat_dict(role=role, username=username, password=password)
    path = creat_path(tag='pwd', username=username)
    msg = save_data(user_dict, path=path)
    if msg:
        return msg
    else:
        return '注册成功！'


def login():
    username, password, role = get_username_pwd()
    # 如果为空，说明不符合格式，则登录失败
    if not username: return "登录失败！"
    path = creat_path('pwd', username=username)
    data = read_data(path=path)
    if not data: return "当前数据库中尚未存在数据，请先进行注册！"
    if password != data.get(username)['password']:
        return "密码错误，请重新登录！"
    else:
        login_user_dict['username'] = username
        login_user_dict['role'] = role
        return f"{username}登录成功！"


def check_one():
    check_user = input("请输入想要查看的用户名:>>>").strip()
    if f"{check_user}_info.json" not in os.listdir(USER_INFO_DIR):
        return f"该用户名{check_user}尚未注册，无法查看！"
    path = os.path.join(USER_INFO_DIR, f"{check_user}_info.json")
    data = read_data(path)
    user_data = data[check_user]
    msg = (f"""
        {user_data.get('username')}信息如下
            male:{user_data.get('male')}
            age:{user_data.get('age')}
            hobby:{user_data.get('hobby')}
            """)
    return msg


def check_all():
    for path in os.listdir(USER_INFO_DIR):
        data = read_data(os.path.join(USER_INFO_DIR, path))
        if not data:
            return "当前数据库中尚未存在数据，请先进行注册！"
        for key in data.keys():
            user_dict = data[key]
            print(f"""{user_dict.get('username')}信息如下
            male:{user_dict.get('male')}
            age:{user_dict.get('age')}
            hobby:{user_dict.get('hobby')}
            """)
    return ''


def quit_system():
    return 'break'
